//
// Created by konglinglong on 2020/9/24.
//

#include <stdio.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <arpa/inet.h>
#include "../../include/osal/osUdp.h"

int32_t OS_UdpInit(int *fd)
{
    *fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == *fd)
    {
        printf("OS_UdpInit : create socket fail: %s\n", strerror(errno));
        return CSP_RC_ER;
    }

    int reuse = 1;
    if(setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(int)) < 0)
    {
        close(*fd);
        *fd = -1;
        printf("OS_UdpInit : Set SO_REUSEADDR error!\n");
        return CSP_RC_ER;
    }

    return CSP_RC_OK;
}

int32_t OS_UdpFinal(int fd)
{
    shutdown(fd, SHUT_RDWR);
    usleep(1000);
    return close(fd);
}

int32_t OS_UdpBind(int fd, const char* ip, uint16_t port)
{
    int32_t ret;
    struct sockaddr_in in_addr;

    in_addr.sin_family = AF_INET;
    in_addr.sin_addr.s_addr = inet_addr(ip);
    in_addr.sin_port = htons(port);
    ret = bind(fd, (const struct sockaddr*)(&in_addr), sizeof(struct sockaddr));
    if(0 != ret)
    {
        printf("OS_UdpBind : Bind error[%s]\n", strerror(errno));
        return CSP_RC_ER;
    }

    return CSP_RC_OK;
}

int32_t OS_UdpConnect(int fd, const char* ip, uint16_t port)
{
    int32_t ret;
    struct sockaddr_in in_addr;

    in_addr.sin_family = AF_INET;
    in_addr.sin_addr.s_addr = inet_addr(ip);
    in_addr.sin_port = htons(port);
    ret = connect(fd, (const struct sockaddr*)(&in_addr), sizeof(struct sockaddr));
    if(0 != ret)
    {
        printf("OS_UdpConnect : Connect error[%s]\n", strerror(errno));
        return CSP_RC_ER;
    }

    return CSP_RC_OK;
}

